package com.ds.infra.rpc.registry.service.impl;

import com.ds.infra.rpc.registry.constant.ZkConstant;
import com.ds.infra.rpc.registry.service.ServiceRegistry;
import com.ds.infra.rpc.registry.util.CuratorUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

import java.util.Map;
import java.util.UUID;

/**
 * 作用：RPC服务注册接口
 *
 * @author WeiShaoying
 */
@Slf4j
public class ZkServiceRegistry implements ServiceRegistry {

    private final CuratorFramework zkClient;
    private final ObjectMapper objectMapper = new ObjectMapper();

    public ZkServiceRegistry(String zkAddress) {
        this.zkClient = CuratorUtils.getZkClient(zkAddress);
    }

    @Override
    public void register(String serviceKey, Map<String, Object> serviceMeta) throws Exception {
        String servicePath = ZkConstant.ZK_BASE_PATH + "/" + serviceKey;
        String nodePath = servicePath + "/" + UUID.randomUUID();

        // 创建持久化服务节点（如果不存在）
        CuratorUtils.createPersistentNode(zkClient, servicePath);

        // 注册临时节点
        zkClient.create()
                .withMode(CreateMode.EPHEMERAL)
                .forPath(nodePath, objectMapper.writeValueAsBytes(serviceMeta));

        log.debug("Registered service: {}", nodePath);
    }

    @Override
    public void unregister(String serviceKey) throws Exception {
        // 实际生产需维护已注册路径，此处简化处理
        log.warn("ZK ephemeral nodes auto-remove on session close");
    }
}
